package com.example.springshell;

import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;

import java.util.Arrays;

@ShellComponent
public class DockerCommands {

    // 启动Docker容器
    @ShellMethod(key = {"start-docker"}, value = "Start a Docker container by its name or ID")
    public void startContainer(String containerIdOrName) {
        ProcessBuilder pb = new ProcessBuilder("docker", "start", containerIdOrName);
        try {
            Process process = pb.start();
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Container " + containerIdOrName + " started successfully.");
            } else {
                System.err.println("Failed to start container " + containerIdOrName);
            }
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
        }
    }

    // 关闭Docker容器
    @ShellMethod(key = {"stop-docker"}, value = "Stop a Docker container by its name or ID")
    public void stopContainer(String containerIdOrName) {
        ProcessBuilder pb = new ProcessBuilder("docker", "stop", containerIdOrName);
        try {
            Process process = pb.start();
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Container " + containerIdOrName + " stopped successfully.");
            } else {
                System.err.println("Failed to stop container " + containerIdOrName);
            }
        } catch (Exception e) {
            System.err.println("An error occurred: " + e.getMessage());
        }
    }
}
